package validator

import (
    "reflect"
    zhongwen "github.com/go-playground/locales/zh"
    ut "github.com/go-playground/universal-translator"
    "github.com/go-playground/validator/v10"
    "github.com/go-playground/validator/v10/translations/zh"
)

var Validate *validator.Validate
var trans ut.Translator

func init() {
    zw := zhongwen.New()
    uni := ut.New(zw, zw)
    trans, _ = uni.GetTranslator("zh")

    Validate = validator.New()
    Validate.RegisterTagNameFunc(func(field reflect.StructField) string {
        label := field.Tag.Get("cn")
        if len(label) == 0 {
            return field.Name
        }
        return label
    })
    zh.RegisterDefaultTranslations(Validate, trans)
}

func TryValidate(struct_object interface{}) (bool, []string) {
	err := Validate.Struct(struct_object)

	errs, ok := err.(validator.ValidationErrors)
	if !ok {
		return true, nil
	}

    var list []string
    for _, e := range errs {
        list = append(list, e.Translate(trans))
	}
	
	if len(list) > 0 {
		return false, list
	}
	return true, nil
}

//ctx.StatusCode(iris.StatusBadRequest)
// for _, err := range err.(validator.ValidationErrors) {
// 	fmt.Println("1..", err.Translate(trans))
// 	fmt.Println("2..", err)
// 	ctx.StatusCode(iris.StatusInternalServerError)
//     ctx.WriteString(err.Translate(trans))
//     // fmt.Println()
//     // fmt.Println(err.Namespace())
//     // fmt.Println(err.Field())
//     // fmt.Println(err.StructNamespace())
//     // fmt.Println(err.StructField())
//     // fmt.Println(err.Tag())
//     // fmt.Println(err.ActualTag())
//     // fmt.Println(err.Kind())
//     // fmt.Println(err.Type())
//     // fmt.Println(err.Value())
//     // fmt.Println(err.Param())
//     // fmt.Println()
// }